import "reflect-metadata";
import express from "express";
import bodyParser from "body-parser";
import {
  useContainer as useContainerRoutingControllers,
  useExpressServer,
} from "routing-controllers";
import { Container } from "typedi";
import dotEnv from "dotenv";
import { logger } from "@vendor/logger";
import sendMessage from "@vendor/dingTalk";

import { HttpErrorMiddleware } from "./middleware/error";
import { LoggingMiddleware } from "./middleware/logging";

import { LoginController } from "./controller/loginController";
import { ListController } from "./controller/accountController";
import { GoodsController } from "./controller/goodsController";

dotEnv.config();

const app = express();
app.set("etag", false);
app.use(bodyParser.json({ limit: "10mb", type: "application/json" }));
app.use(bodyParser.urlencoded({ limit: "10mb", extended: true }));

const cors = require("cors");
app.use(cors());

useExpressServer(app, {
  controllers: [LoginController, ListController, GoodsController],
  middlewares: [HttpErrorMiddleware, LoggingMiddleware],
  defaultErrorHandler: false,
});

useContainerRoutingControllers(Container);

app.listen(3000, () => {
  console.log("Example app listening on port 3000!");
});

process.on("uncaughtException", (err, origin) => {
  const errMsg = `uncaughtException 全局异常\n捕获的异常：${err}\n异常的来源：${origin}`;
  logger.error(errMsg);
  sendMessage("全局异常uncaughtException", errMsg);
});

process.on("unhandledRejection", (err, origin) => {
  const errMsg = `unhandledRejection Promise未绑定异常\n捕获的异常：${err}\n异常的来源：${origin}`;
  logger.error(errMsg);
  sendMessage("全局异常unhandledRejection", errMsg);
});
